<?php

declare(strict_types=1);

namespace Ysy\HyperfImport\Importer\Validator;

use Psr\Http\Message\UploadedFileInterface;
use Ysy\HyperfImport\Importer\Exception\FileNotExistException;
use Ysy\HyperfImport\Importer\Exception\UnsupportedFileTypeException;

class FileValidator
{
    protected array $allowedMimes = [
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // xlsx
        'application/vnd.ms-excel', // xls
        'text/csv', // csv
    ];

    protected array $allowedExtensions = ['xlsx', 'xls', 'csv'];

    /**
     * 验证文件的 MIME 类型和扩展名
     * @param UploadedFileInterface $file
     * @return void
     * @throws HttpException
     */
    public function validate(UploadedFileInterface $file): array
    {
        if (!$file->isValid()) {
            throw new FileNotExistException($file->getClientFilename);
        }

        // 获取 MIME 类型
        $fileMimeType = $file->getClientMediaType();
        if (!in_array($fileMimeType, $this->allowedMimes)) {
            throw new UnsupportedFileTypeException($fileMimeType);
        }

        // 获取扩展名
        $originalName = $file->getClientFilename();
        $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
        if (!in_array($extension, $this->allowedExtensions)) {
            throw new UnsupportedFileTypeException($extension);
        }

        return compact('fileMimeType', 'originalName', 'extension');
    }
}